<template>
  <div>
    <!-- 背景card -->
    <el-card shadow="hover" :body-style="{ padding: '20px' }">
      <!-- 添加按钮 -->
      <el-button
        type="primary"
        size="default"
        :icon="Plus"
        @click="addTradeMark"
        >添加</el-button
      >
      <!-- 表格 -->
      <el-table
        border
        :data="tmObj.records"
        v-loading="loading"
        style="margin: 10px 0"
      >
        <el-table-column
          label="序号"
          align="center"
          width="90px"
          type="index"
        ></el-table-column>
        <el-table-column label="品牌名称" prop="tmName"></el-table-column>
        <el-table-column label="品牌LOGO">
          <template #="{ row, $index }">
            <a :title="row.tmName">
              <img
                :src="row.logoUrl"
                alt=""
                style="width: 100px; height: 60px; border-radius: 10px"
              />
            </a>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #="{ row, $index }">
            <el-button
              type="warning"
              size="small"
              :icon="Edit"
              @click="updateTrademark(row)"
            ></el-button>
            <el-popconfirm :title="`你确定删除${row.tmName}?`" width="250px"  :icon="Delete" @confirm="handler(row)">
              <template #reference>
                <el-button type="danger" size="small" :icon="Delete"></el-button>
              </template>
            </el-popconfirm>
            
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页器 -->
      <!--      @size-change="sizeChange"
        @current-change="currentChange" -->
      <el-pagination
        @size-change="sizeChange"
        @current-change="getTradeMarkList"
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :total="tmObj.total"
        :pager-count="7"
        :page-sizes="[3, 5, 7]"
        layout=" prev, pager, next, jumper,->,sizes,total "
        background
      >
      </el-pagination>

      <!-- Dialog对话框 -->
      <el-dialog
        v-model="dialogFormVisible"
        :title="tmParams.id ? '修改品牌' : '添加品牌'"
      >
        <el-form
          label-width="100px"
          style="width: 80%"
          :model="tmParams"
          :rules="rules"
          ref="formRef"
        >
          <!-- 获取品牌名称的地方 -->
          <el-form-item label="品牌名称" prop="tmName">
            <el-input autocomplete="off" v-model="tmParams.tmName" />
          </el-form-item>
          <!-- 获取品牌LOGO的地方 -->
          <el-form-item label="品牌LOGO" prop="logoUrl">
            <el-upload
              class="avatar-uploader"
              action="/api/admin/product/fileUpload"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
            >
              <img
                v-if="tmParams.logoUrl"
                :src="tmParams.logoUrl"
                class="avatar"
              />
              <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            </el-upload>
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取消</el-button>
            <el-button type="primary" @click="addOrUpdate">确定</el-button>
          </span>
        </template>
      </el-dialog>
    </el-card>
  </div>
</template>

<script setup lang="ts">
// 引入elment需要的数据类型
import type { UploadProps, FormRules, FormInstance } from "element-plus";
//引入消息提示框组件
import { ElMessage } from "element-plus";
// 引入数据类型
import type {
  trademark,
  trademarkResponseData,
} from "@/api/product/trademark/model/trademark";
// 引入接口
import {
  reqTradeMarkList,
  reqAddOrUpdateTradeMark,
  reqDeleteTradeMark
} from "@/api/product/trademark/trademark";
import {
  Delete,
  Edit,
  Search,
  Share,
  Upload,
  Plus,
} from "@element-plus/icons-vue";
import { ref, onMounted, reactive, nextTick } from "vue";
//保存分页器前页码动态数据
let currentPage = ref<number>(1);
// 保存当前页面显示几条数据
let pageSize = ref<number>(3);
// 定义控制加载效果的响应式数据
let loading = ref<boolean>(false);
// 控制对话框显示与隐藏
let dialogFormVisible = ref<boolean>(false);
// 存储组件实例
const formRef = ref<FormInstance>();
// 定义请求服务器返回的品牌数据
let tmObj = reactive<trademarkResponseData>({
  total: 0,
  records: [],
});
// 定义收集新增品牌数据
let tmParams = reactive<trademark>({
  tmName: "",
  logoUrl: "",
});
// 挂载完成后获取一次列表数据
onMounted(() => {
  getTradeMarkList();
});

// 获取列表数据    分页器底层传参page
const getTradeMarkList = async (page: number = 1) => {
  // 请求前加载
  loading.value = true;
  // 整理参数
  currentPage.value = page;
  // 发请求获取数据
  let result = await reqTradeMarkList(currentPage.value, pageSize.value);
  //保存服务器返回的数据
  tmObj.records = result.records; //品牌对象
  tmObj.total = result.total; //数据总数
  //    获取数据后不加载
  loading.value = false;
};

// 当选择每一页几条数据发生改变时
const sizeChange = (limit: number) => {
  // 整理参数
  pageSize.value = limit;
  // 再次发请求
  getTradeMarkList();
};

// 点击确定按钮添加或修改品牌,发请求
const addOrUpdate = async () => {
  formRef.value?.validate(async (success) => {
    if (success) {
      // 发请求
      await reqAddOrUpdateTradeMark(tmParams);
      //  对话框关闭
      dialogFormVisible.value = false;
      // 再次获取列表数据
      // 根据id判断修改还是更新,更新返回第一页,修改停在当前页
      getTradeMarkList(tmParams.id ? currentPage.value : 1);
      ElMessage({
        message: tmParams.id ? "修改品牌成功" : "添加品牌成功",
        type: "success",
      });
    } else {
      ElMessage({
        message: "看清规则",
        type: "error",
      });
    }
  });
};

// 图片上传成功
const handleAvatarSuccess: UploadProps["onSuccess"] = (
  response,
  uploadFile
) => {
  tmParams.logoUrl = response.data;
};

// 图片上传前的钩子---约束条件
const beforeAvatarUpload: UploadProps["beforeUpload"] = (rawFile) => {
  //图片相关的信息
  //外层约束类型
  if (
    rawFile.type == "image/jpeg" ||
    rawFile.type == "image/png" ||
    rawFile.type == "image/gif"
  ) {
    //约束大小1024B->1K->1M->1G->1T
    if (rawFile.size / 1024 / 1024 <= 5) {
      return true;
    }
  } else {
    return false;
  }
};

// 点击添加按钮回调  清空上次数据
const addTradeMark = () => {
  // 弹框出现
  dialogFormVisible.value = true;
  tmParams.id = "";
  tmParams.logoUrl = "";
  tmParams.tmName = "";

  // nextTick响应式数据发生改变时,页面重新渲染,过去最新DOM
  nextTick(() => {
    formRef.value?.resetFields();
  });
};

// 修改按钮的回调
const updateTrademark = (row: trademark) => {
  // 对话框显示
  dialogFormVisible.value = true;
  // nextTick响应式数据发生改变时,页面重新渲染,过去最新DOM
  nextTick(() => {
    formRef.value?.resetFields();
    // 获取当前品牌数据
    tmParams.logoUrl = row.logoUrl;
    tmParams.tmName = row.tmName;
    tmParams.id = row.id;
  });
};

// 自定义表单验证
const validatetmName = (rule: any, value: any, next: any) => {
  if (value.length >= 2 && value.length < 10) {
    next();
  } else {
    next(new Error("品牌名称不小于2,不大于10"));
  }
};

// 表单验证规则
const rules = reactive<FormRules>({
  tmName: [{ required: true, trigger: "blur", validator: validatetmName }],
  logoUrl: [{ required: true, message: "请上传logo图片" }],
});

// 删除按钮弹框确定事件---删除某一个品牌数据
const handler =async (row:trademark)=>{
  try {
   await reqDeleteTradeMark(row.id)
   ElMessage({
    type:'success',
    message:`删除${row.tmName}成功`
   });
  //  再次获取最新数据
  getTradeMarkList(currentPage.value)
  } catch (error) {
    
  }
    
}
</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
